package com.itxialu.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常捕获
 *
 * @author shkstart
 * @create 2022-09-28 22:35
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException SQLException) {
        log.error(SQLException.getMessage());

        //完善
        //判断错误信息包含的字段
        if (SQLException.getMessage().contains("Duplicate entry")) {
            //根据数组分隔，拿到一个数组对象
            String[] split = SQLException.getMessage().split(" ");
            String Msg = split[2];//取String[]数组，下标为2的数据
            return R.error("账号" + Msg + "已存在！！");
        }
        return R.error("未知错误！");
    }


    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException SQLException) {
        log.error(SQLException.getMessage());

        return R.error(SQLException.getMessage());
    }
}
